﻿using System;

namespace KingTools.Utils
{
    public class EncryUtil
    {
        /// <summary>
        ///     客户端通过服务端发送的加密字节数组加密待发送的内容，加密内容不包含字节长度
        /// </summary>
        /// <param name="source">待加密的字节数组</param>
        /// <param name="key">服务端发送的密钥字节数组</param>
        /// <returns></returns>
        public static byte[] encrypt(byte[] source, byte[] key)
        {
            try
            {
                var des = new byte[source.Length];
                // 总的段数
                int len = source.Length/key.Length + (source.Length%key.Length == 0 ? 0 : 1);
                for (int j = 0; j < len; j++)
                {
                    for (int i = j*len; i < (j + 1)*len*key.Length && i < source.Length; i++)
                    {
                        des[i] = (byte) (source[i] ^ (key[(i + j)%(key.Length)]));
                    }
                }
                return des;
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
            return null;
        }
    }
}